import hashlib
import time
import re
# 操作html界面的
from selenium.webdriver.common.by import By

from automate_testing.tool.DButils import DButils
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def get_userId(username):
    select_id_sql = 'select id from user where username=%s'
    userId = DButils().select(select_id_sql, (username,))[0][0]
    return userId

class BankcardOperate:
    def enter_bankcard_page(func):
        def wrapper(*args, **kwargs):
            # 进入银行卡管理界面
            driver=args[0]
            driver.find_element(By.XPATH, '//*[@id="leftbaraside"]/div[2]/nav/ul/li[4]/a').click()
            time.sleep(1)
            driver.find_element(By.XPATH, '//*[@id="leftbaraside"]/div[2]/nav/ul/li[4]/ul/li[3]/a').click()
            time.sleep(1)

            # 调用原始函数
            result = func(*args, **kwargs)
            return result

        return wrapper

    @staticmethod
    @enter_bankcard_page
    def insert_bankcard(driver,cardBank,kind,cardNum):

        driver.find_element(By.XPATH,'//*[@id="bankCard_add_modal_btn"]').click()
        time.sleep(1)

        # 弹出了一个新增银行卡的模态框
        # 等待模态框中的按钮可点击
        try:
            # 银行名称
            input_cardBank = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '//*[@id="cardBank_add_input"]'))
            )
            input_cardBank.send_keys(cardBank)
            # 卡类型
            # 等待模态框中的单选按钮（借记卡）可点击
            if kind == '借记卡':
                radio = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="bankCardAddModal"]/div/div/div[2]/form/div[2]/div[1]/div/label[1]'))
                )
                # 点击单选按钮（借记卡）
                radio.click()
            else:
                radio = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="bankCardAddModal"]/div/div/div[2]/form/div[2]/div[1]/div/label[2]'))
                )
                # 点击单选按钮（信用卡）
                radio.click()
            # 银行卡号
            input_cardNum = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '//*[@id="cardNum_add_input"]'))
            )
            input_cardNum.send_keys(cardNum)
            # 保存按钮
            save_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//*[@id="bankCard_save_btn"]'))
            )
            save_button.click()
            time.sleep(3)
        except  Exception as e:
            print(e)

    @staticmethod
    def insert_clear_sql(cardNum):
        sql='delete from bankcard where cardNum=%s'
        DButils().update(sql,(cardNum,))

    @staticmethod
    def get_user_card_number(username,cardNum):
        BankcardOperate.insert_clear_sql(cardNum)
        userId=get_userId(username)

        select_card_sql = 'select cardNum from bankcard where userId=%s'
        return len(DButils().select(select_card_sql,(userId,)))

    @staticmethod
    def insert_card_sql(username,cardBank,kind,cardNum,balance = 10000.00,defaultl=-1):
        if not cardNum:
            return
        userId=get_userId(username)
        if defaultl==-1:
            card_number = BankcardOperate.get_user_card_number(username, cardNum)
            defaultl = 0 if card_number > 0 else 1
        type1 = 1 if kind == '借记卡' else 2
        insert_card_sql = 'insert into bankcard(cardBank,type,cardNum,userId,balance,defaultl) values(%s,%s,%s,%s,%s,%s)'
        DButils().update(insert_card_sql, (cardBank, type1, cardNum, userId, balance, defaultl))


    @staticmethod
    def get_insert_result(cardBank,kind,cardNum):
        type1 = 1 if kind == '借记卡' else 2
        sql='select * from bankcard where cardBank=%s and type=%s and cardNum=%s'
        return DButils().select(sql,(cardBank,type1,cardNum))

    @staticmethod
    @enter_bankcard_page
    def delete_card(driver,username):
        userId = get_userId(username)
        # 删除第一张卡
        cardNum=driver.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[2]/div/div/div[2]/h4[1]').text.replace('卡号：','')
        driver.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[2]/div/div/div[1]/ul/li/button[2]').click()
        return userId,cardNum

    @staticmethod
    def confirm_deletion(driver):
        confirm_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button[1]'))
        )
        confirm_button.click()
        time.sleep(6)


    @staticmethod
    def cancel_deletion(driver):
        cancel_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button[2]'))
        )
        cancel_button.click()
        time.sleep(1)
        prompt_button=WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH,'/html/body/div[2]/div[2]/div/div/div/div/div/div/div/div[4]/button'))
        )
        prompt_button.click()


    @staticmethod
    def get_delete_result(userId,cardNum):
        select_sql='select * from bankcard where userId=%s and cardNum=%s'
        data = DButils().select(select_sql,(userId,cardNum))
        return len(data)

    @staticmethod
    def get_before_card(driver,username):
        userId=get_userId(username)
        header_info=driver.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[2]/div/div/div[1]/div').text()
        pattern = r"([\u4e00-\u9fa5]+银行)|([\u4e00-\u9fa5]+卡)"
        match  = re.search(pattern, header_info)
        if match:
            # 检查哪个捕获组匹配成功
            bank = match.group(1)
            type1 = match.group(2)
        body_info=driver.find_element(By.XPATH,'/html/body/div/div/main/div/div/div[2]/div/div/div[2]').text()
        pattern = r"卡号：(\d+)"
        match = re.search(pattern, body_info)
        if match:
            cardNum = match.group(1).replace('卡号：','')
        return userId,bank,type1,cardNum

    @staticmethod
    def edit_clear_sql(username):
        userId=get_userId(username)
        sql='delete from bankcard where userId=%s'
        DButils().update(sql,(userId,))

    @staticmethod
    @enter_bankcard_page
    def edit_bankcard(driver,cardBank,kind,cardNum):

        # 编辑银行卡
        driver.find_element(By.XPATH, '/html/body/div/div/main/div/div/div[2]/div/div/div[1]/ul/li/button[1]').click()
        time.sleep(1)

        # 弹出了一个编辑银行卡的模态框
        # 等待模态框中的按钮可点击
        try:
            # 银行名称
            input_cardBank = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '//*[@id="cardBank_update_input"]'))
            )
            input_cardBank.clear()
            input_cardBank.send_keys(cardBank)
            # 卡类型
            # 等待模态框中的单选按钮（借记卡）可点击
            if kind == '借记卡':
                radio = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="bankCardUpdateModal"]/div/div/div[2]/form/div[2]/div[1]/div/label[1]'))
                )
                # 点击单选按钮（借记卡）
                radio.click()
            else:
                radio = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable(
                        (By.XPATH, '//*[@id="bankCardUpdateModal"]/div/div/div[2]/form/div[2]/div[1]/div/label[2]'))
                )
                # 点击单选按钮（信用卡）
                radio.click()
            # 银行卡号
            input_cardNum = WebDriverWait(driver, 10).until(
                EC.visibility_of_element_located((By.XPATH, '//*[@id="cardNum_update_input"]'))
            )
            input_cardNum.clear()
            input_cardNum.send_keys(cardNum)
            # 更新按钮
            updeate_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.XPATH, '//*[@id="bankCard_update_btn"]'))
            )
            updeate_button.click()
            time.sleep(3)
        except  Exception as e:
            print(e)
    @staticmethod
    def get_edit_result(username,cardBank,kind,cardNum):
        userId=get_userId(username)
        type1 = 1 if kind == '借记卡' else 2
        select_sql='select * from bankcard where userId=%s and cardBank=%s and type=%s and cardNum=%s'
        data=DButils().select(select_sql,(userId,cardBank,type1,cardNum))
        return len(data)

    @staticmethod
    def delete_user_card(username):
        # 删除所有卡
        userId=get_userId(username)
        select_sql='select * from bankcard where userId=%s'
        data=DButils().select(select_sql,(userId,))
        return len(data)
"""
mysql> desc bankcard;
+----------+---------------+------+-----+---------+----------------+
| Field    | Type          | Null | Key | Default | Extra          |
+----------+---------------+------+-----+---------+----------------+
| id       | int           | NO   | PRI | NULL    | auto_increment |
| cardBank | varchar(20)   | YES  |     | NULL    |                |
| type     | int           | YES  |     | NULL    |                |
| cardNum  | varchar(20)   | YES  |     | NULL    |                |
| userId   | int           | YES  |     | NULL    |                |
| balance  | decimal(15,2) | YES  |     | NULL    |                |
| defaultl | int           | YES  |     | NULL    |                |
+----------+---------------+------+-----+---------+----------------+

mysql> select * from bankcard;
+----+--------------+------+--------------------+--------+----------+----------+
| id | cardBank     | type | cardNum            | userId | balance  | defaultl |
+----+--------------+------+--------------------+--------+----------+----------+
|  1 | 中国建设银行 |    2 | 12345678945213124  |      1 | 20216.20 |        1 |
|  3 | 阿萨         |    1 | 1223563434534567   |      4 | 40000.00 |        1 |
"""